package wangm.netty.udptest2;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * description
 *
 * @author zk
 * @since 2018/7/21
 */
public class UdpClient {

    public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup())
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new MyUdpEncoder());
        ChannelFuture channelFuture = bootstrap.bind(9900).sync();

        String message = null;
        while (!(message = new Scanner(System.in).nextLine()).contains("EOF")) {
            channelFuture.channel().writeAndFlush(Unpooled.buffer().writeBytes(message.getBytes())).addListener((f) -> {
                System.out.println(f.isSuccess());
                if (!f.isSuccess()) {
                    f.cause().printStackTrace();
                }
            });
        }
        channelFuture.channel().closeFuture().sync();

    }

    //    private static class MyUdpEncoder extends MessageToMessageEncoder<ByteBuf> {
//        @Override
//        protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
//            InetSocketAddress inetSocketAddress = new InetSocketAddress("192.168.24.28", 8989);
//            out.add(new DatagramPacket(Unpooled.buffer().writeBytes(msg),inetSocketAddress));
//        }
//    }
    private static class MyUdpEncoder extends ChannelOutboundHandlerAdapter {
        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            if(msg instanceof ByteBuf){
                DatagramPacket datagramPacket = new DatagramPacket((ByteBuf) msg,new InetSocketAddress("192.168.24.28",8989));
                ctx.write(datagramPacket,promise);
            }
        }

    }
}

